package grsu.epam.airline.action;

import grsu.epam.airline.form.EmployeeModifyForm;
import grsu.epam.airline.service.EmployeeService;
import grsu.epam.airline.service.SpecialityService;
import grsu.epam.airline.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class EmployeeAddAction extends Action {
	String target = ForwardActionTo.EMPLOYEES;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		UserService userService = new UserService();
		if (userService.checkUser(session.getAttribute("auth"),
				ConstantUserRole.DISPATCHER)) {
			EmployeeModifyForm input = (EmployeeModifyForm) form;
			EmployeeService employeeService = new EmployeeService();
			SpecialityService specialityService = new SpecialityService();
			request.setAttribute("specialities",
					specialityService.getAllSpeciality());
			if ((input.getSpecialityId() == -1) || (input.getName().isEmpty())
					|| (input.getSurname().isEmpty())) {
				ActionMessages errors = new ActionMessages();
				errors.add("fieldEmpty", new ActionMessage("error.empty"));
				target = ForwardActionTo.ERROR;
				saveErrors(request, errors);
			} else {
				employeeService.addEmployee(input.getSpecialityId(),
						input.getName(), input.getSurname());
				request.setAttribute("employees",
						employeeService.getAllEmployee());
				target = ForwardActionTo.EMPLOYEES;
			}
		} else {
			target = ForwardActionTo.ERRORUSER;
		}
		return mapping.findForward(target);
	}
}
